import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import Taro from '@tarojs/taro'
import tetris from '../pages/game/space/tetris/vuex/store'
Vue.use(Vuex)

export interface IUser {
  age: number;
  userId: number;
  avatar: string;
  score: number;
  nickname: string;
  totSize: number;
  sex: string;
  rank: number;
  bmi: string;
  chrdse: string;
  gds: string;
  height: string;
  weight: string;
  mobile: string;
  moca: string;
  level: number;
  mmse: string;
  sas: string;
}

interface State {
  token: string,
  user: Partial<IUser>,
  evaluation: Record<string, string | number>,
  exam: Record<string, string | number>,
  system: Record<string, string | number>
}

const state: State = {
  token: '',
  user: {},
  evaluation: {},
  exam: {},
  system: {}
}

const mutations = {
  setToken: (state: State, token: string) => {
    state.token = token
  },
  setUser: (state: State, user: Object) => {
    state.user = user
  },
  setEvaluation: (state: State, evaluation: State['evaluation']) => {
    state.evaluation = evaluation
  },
  setExam: (state: State, exam: State['exam']) => {
    state.exam = exam
  },
  setSystem: (state: State, system: State['system']) => {
    const { windowWidth: innerWidth, windowHeight: innerHeight } = system
    state.system = { ...system, innerWidth, innerHeight }
  }
}

const actions = {}

const getters = {
  token: (state: State) => state.token, // 用户令牌
  user: (state: State) => state.user, // 用户信息
  evaluation: (state: State) => state.evaluation,
  exam: (state: State) => state.exam,
  system: (state: State) => state.system
}

const plugins = [
  createPersistedState({
    key: 'vuex',
    paths: ['token', 'user', 'system'],
    storage: {
      getItem: (key: string) => Taro.getStorageSync(key),
      setItem: (key: string, value: any) => Taro.setStorageSync(key, value),
      removeItem: (key: string) => Taro.removeStorageSync(key)
    }
  })
]

const store = new Vuex.Store({
  state,
  mutations,
  actions,
  getters,
  plugins,
  modules: {
    tetris
  }
})

export default store
